package com.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Zhang Guangyong
 * @desacription 测试帐号类
 * @date 2019年08月15日 16:50
 */
public class Account {

    private final ReentrantLock lock = new ReentrantLock();

    private final Condition cond = lock.newCondition();

    private String accountNo;

    private double balance;

    // 标识帐户中是否已有存款
    private boolean flag = false;

    public Account() {
    }

    public Account(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    /**
     * 取钱方法
     *
     * @param drawAmount : 取多少
     * @author 张广勇
     * @date 2019/8/19 9:25
     */
    public void draw(double drawAmount) {
        System.out.println(Thread.currentThread().getName() + "尝试取钱");
        lock.lock();
        try {
            if (!flag) {
                System.out.println(Thread.currentThread().getName() + "阻塞");
                cond.await();
            } else {
                //吐钞
                System.out.println(Thread.currentThread().getName() + "取出了" + drawAmount);
                //修改余额
                balance -= drawAmount;
                System.out.println("余额为: " + balance);
                flag = false;
                //唤醒其他线程
                cond.signalAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void deposit(double depositAmount) {
        lock.lock();
        try {
            if (flag) {
                System.out.println(Thread.currentThread().getName() + "阻塞");
                cond.await();
            } else {
                //吐钞
                System.out.println(Thread.currentThread().getName() + "存入了" + depositAmount);
                //修改余额
                balance += depositAmount;
                System.out.println("余额为: " + balance);
                flag = true;
                //唤醒其他线程
                cond.signalAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


//    public void draw(double drawAmount) {
//        lock.lock();
//        try {
//            if (balance >= drawAmount) {
//                //吐钞
//                System.out.println(Thread.currentThread().getName() + "取出了" + drawAmount);
//
//                try {
//                    Thread.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                //修改余额
//                balance -= drawAmount;
//                System.out.println("余额为: " + balance);
//            } else {
//                System.out.println(Thread.currentThread().getName() + "取钱失败 余额不足");
//            }
//        } finally {
//            lock.unlock();
//        }
//
//    }

}
